<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <h2>扫码登录 案例</h2>
    <p>Nodejs + Mysql + Vue + Uni-app</p>
    <div v-if="ScanCodeShow">
      <div class="stateQRcode" >
        <div class="successQRcode" v-if="successShow">
          <img src="@/assets/img/success.png" alt="">
          <p>扫码成功</p>
        </div>
        <img v-if="base64QRcode" :src="base64QRcode.QRcode" alt="">
      </div>
      <div class="stateText">
        <p>{{tipsText}}</p>
      </div>
    </div>
    <div v-else>
      登录成功
    </div>
  </div>
</template>

<script setup>
// 引入socket.io
import sockets from '@/assets/js/socket.io.min.js'
import { reactive, ref } from 'vue'

// 定义状态
let socket = reactive({}) // 保存 socket链接
let base64QRcode = reactive({}) // 保存后端给的二维码和uuid
let timerCheck = reactive({}) // 保存定时器
const tipsText = ref('请扫码') // 提示文字
const successShow = ref(false) // 是否显示扫码成功
const ScanCodeShow = ref(true)

socket = sockets.io('ws://localhost:3000')

// 定义方法
const getQRcode = () => {
  // 发起获取登录二维码请求
  socket.emit('getQRcode')
}

// 定义socket事件

// 获取二维码数据
socket.on('sendQRcode', res => {
  // console.log(res)
  base64QRcode = res
})

// 等待扫码
socket.on('waitScanCode', res => {
  if (!successShow.value) {
    tipsText.value = '等待用户扫码'
  }
})
// 扫码成功
socket.on('SuccessScanCode', res => {
  localStorage.setItem('userInfo', res)
  tipsText.value = `扫码成功用户信息为：${res}`
  // ScanCodeShow.value = false
  socket.disconnect()
  clearInterval(timerCheck)
})
// 轮询，每隔1秒向服务器查看是否扫码登录成功
timerCheck = setInterval(() => { socket.emit('checkScanCode', base64QRcode.uuid) }, 1000)

// 已扫码但未确认
socket.on('ScanCodeing', (res) => {
  if (res !== base64QRcode.uuid) {
    return false
  }
  successShow.value = true
  tipsText.value = '您已扫码，请在手机上确认登录！'
  socket.emit('deteleTimer', base64QRcode.uuid)
})

// 如果二维码超时
socket.on('ScanCodeOvertime', (value) => {
  if (value === base64QRcode.uuid) {
    successShow.value = false
    getQRcode()
  }
// console.log('二维码已经重新获取')
})
// 调用
getQRcode()
</script>

<style lang='less' scoped>
.home{
  display:flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  flex-wrap: wrap;
  text-align: center;
  .stateQRcode{
    position: relative;
    margin: 20px;
    .successQRcode{
      position:absolute;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background: rgba(0, 0, 0, 0.5);
      color:white;
      img{
        width: 50px;
        height: 50px;
      }
    }
  }
  .stateText{
    border-radius: 25px;
    background: rgba(0, 0, 0, 0.5);
    color:white;
    padding: 0 20px;
  }
}
</style>
